/**
 * @author Fang Lu, fanglupku@gmail.com
 * 2012-2-20
 */
package com.autotag.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.autotag.entity.Tag;

import fanglu.util.StringDealer;

public class TagDao {
	private static boolean checkExist(Connection conn,
			Tag tag) {
		try {
			Statement stm = conn.createStatement();
			ResultSet rs = stm
					.executeQuery("select id from tag where name = '"
							+ tag.getName() + "'");
			if (rs.next()) {
				return true;// the user already exists
			} else {
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return true;
		}
	}
	
	public static boolean insertTag(Connection conn,
			Tag tag) {
		if (tag.getName() == null) {
			return false;
		}
		if (checkExist(conn, tag)) {
			System.err.println("Tag:" + tag.getName()
					+ " already exists in database");
			return false;// the user already exists
		}
		try {
			if (tag.getId() < 0) {
				PreparedStatement pst = conn
						.prepareStatement("insert into tag (name, ref) values (?,?)");
				pst.setString(1, StringDealer.getStringForMaxLength(Tag.MAX_LENGTH_NAME,
						tag.getName()));
				pst.setString(2, StringDealer.getStringForMaxLength(Tag.MAX_LENGTH_REF,
						tag.getRef()));
				pst.executeUpdate();
				pst.close();
			} else {
				PreparedStatement pst = conn
						.prepareStatement("insert into tag (id, name, ref) values (?,?,?)");
				pst.setInt(1, tag.getId());
				pst.setString(2, StringDealer.getStringForMaxLength(Tag.MAX_LENGTH_NAME,
						tag.getName()));
				pst.setString(3, StringDealer.getStringForMaxLength(Tag.MAX_LENGTH_REF,
						tag.getRef()));
				pst.executeUpdate();
				pst.close();
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public static List<Tag> getAllTag(Connection conn){
		List<Tag> resultList = new ArrayList<Tag>();
		String sqlString = "select id,name,ref from tag";
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet resultSet = null;
			resultSet = stmt.executeQuery(sqlString);
			while (resultSet.next()) {
				int thisId = resultSet.getInt(1);
				String thisName = resultSet.getString(2);
				String thisRef = resultSet.getString(3);
				Tag thisEntity = new Tag(thisId, thisName, thisRef);
				resultList.add(thisEntity);
			}
			resultSet.close();
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}
}
